package com.base.leetcode;

import com.base.dataStructure.Tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: hdhao
 * @Create: 2023/4/5 - 19:46
 * @Version: v1.0
 */
public class Leetcode104_1 {

    //递归实现
    public int minDepth(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = minDepth(node.left);
        int right = minDepth(node.right);
        if (left == 0) {
            return right + 1;
        }
        if (right == 0) {
            return left + 1;
        }
        return Integer.min(left,right) + 1;
    }

    //层序遍历实现(遇到的第一个叶子节点所在的层就是最小深度)
    public int minDepth2(TreeNode node) {
        if (node == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(node);
        //记录每层有几个元素
        int depth = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left == null && poll.right == null) {
                    return depth;
                }
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        }
        return depth;
    }
}
